/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.open.api.core.service.processor.base.pre;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.component.open.api.core.service.processor.base.AbstractOpenApiServiceProcessor;
import info.peigen.hotpot.component.open.api.facade.Api;
import info.peigen.hotpot.component.open.api.facade.OpenApiServiceFacade;
import info.peigen.hotpot.component.open.api.facade.processor.base.OpenApiProcessor;
import info.peigen.hotpot.component.open.api.facade.processor.base.OpenApiProcessorServiceContext;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.AppContext;
import org.noear.solon.core.bean.LifecycleBean;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * <b>(OpenApiFacadeExecuteProcessor)</b>
 * 封装业务Api调用
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/7/28
 */
@Slf4j
@SuppressWarnings("rawtypes")
@Component
public class OpenApiFacadeExecuteProcessor extends AbstractOpenApiServiceProcessor implements OpenApiProcessor, LifecycleBean {
    @Inject
    protected AppContext                        context;
    private   Map<String, OpenApiServiceFacade> openApiServiceMap;

    @Override
    public Integer level() {
        return 11;
    }

    @Override
    public void execute(OpenApiProcessorServiceContext serviceContext) {
        Api                  api    = serviceContext.getApi();
        OpenApiServiceFacade facade = openApiServiceMap.get(api.getApiCode());
        Assert.notNull(facade, () -> new UnsupportedOperationException("Api服务未发现,apiCode=" + api.getApiCode()));
        facade.execute(serviceContext);
    }

    @Override
    public void start() {
        Map<String, OpenApiServiceFacade> beanMap = context.getBeansMapOfType(OpenApiServiceFacade.class);
        this.openApiServiceMap = beanMap.entrySet().stream().filter(m -> StrUtil.isNotEmpty(m.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        log.debug("[{}]", ArrayUtil.join(this.openApiServiceMap.keySet().toArray(), "\",\""));
    }
}